package com.phuc.game.tankshooter.common;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;

public class Utility {

	public static double getRotationFromLine(
			float x1, float y1, float x2, float y2) {
		double rotation = Math.atan((
				(double)x1 - (double)x2)
				/ ((double)y2 - (double)y1));
		double rotationDeg = Math.toDegrees(rotation);
		return rotationDeg;
	}
	
	public static void unbindDrawable(View view) {
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
			view.setBackgroundDrawable(null);
		}
		
		if (view instanceof ImageView) {
			ImageView img = (ImageView) view;
			try {
				if (img.getDrawable() != null) {
					Bitmap bmp = ((BitmapDrawable)img.getDrawable()).getBitmap();
					bmp.recycle();
				}
			} catch(Exception ex) { }
			
			img.setImageBitmap(null);
		}
		
		if (view instanceof AdapterView) {
			AdapterView viewGroup = (AdapterView) view;
			for (int i = viewGroup.getChildCount() - 1; i > -1; i--) {
				unbindDrawable(viewGroup.getChildAt(i));
			}
			return;
		}
		
		if (view instanceof ViewGroup) {
			ViewGroup viewGroup = (ViewGroup) view;
			for (int i = viewGroup.getChildCount() - 1; i > -1; i--) {
				unbindDrawable(viewGroup.getChildAt(i));
			}
			viewGroup.removeAllViews();
		}
	}
	
	public static void savePreferenceInt(String key, int value, Activity activity) {
		SharedPreferences.Editor editor = activity.getPreferences(Context.MODE_PRIVATE).edit();
		editor.putInt(key, value);
		editor.commit();
	}
	
	public static int getPreferenceInt(String key, int defaultValue, Activity activity) {
		SharedPreferences prefs = activity.getPreferences(Context.MODE_PRIVATE);
		return prefs.getInt(key, defaultValue);
	}
}
